package com.ruoyi.training.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {

//    @Value("${file.upload.root-path}")
    private String uploadRootPath;

    // 记录文件夹保存路径的映射
    private Map<String, String> folderPaths = new HashMap<>();

    /**
     * 提供图片访问接口，供前端通过URL访问图片
     */
    @GetMapping("/api/files/image")
    public void getImage(HttpServletResponse response,
                         @RequestParam("relativePath") String relativePath) {
        // 设置默认响应类型
        response.setContentType("image/*");

        try {
            // 解码URL中的相对路径
            String decodedPath = java.net.URLDecoder.decode(relativePath, "UTF-8");
            // 替换URL路径分隔符为系统文件分隔符
            decodedPath = decodedPath.replace("/", File.separator);
            
            // 构建完整文件路径
            File imageFile = new File(uploadRootPath, decodedPath);

            // 校验文件是否存在且是文件
            if (!imageFile.exists() || !imageFile.isFile()) {
                response.sendError(HttpStatus.NOT_FOUND.value(), "图片文件不存在");
                return;
            }

            // 校验是否为图片文件
            String mimeType = Files.probeContentType(imageFile.toPath());
            if (mimeType == null || !mimeType.startsWith("image/")) {
                response.sendError(HttpStatus.BAD_REQUEST.value(), "请求的文件不是图片类型");
                return;
            }

            // 设置正确的Content-Type
            response.setContentType(mimeType);

            // 读取文件并写入响应流
            try (InputStream in = new FileInputStream(imageFile);
                 OutputStream out = response.getOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
            }

        } catch (Exception e) {
            try {
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "图片访问失败");
            } catch (IOException ex) {
                // 处理响应写入异常
            }
        }
    }


    /**
     * 处理文件夹上传
     * @param files 上传的文件数组
     * @param folderStructure 文件夹结构信息
     * @param originalFolderName 原始文件夹名称
     * @return 上传结果
     */
    @PostMapping("/folder")
    public ResponseEntity<?> uploadFolder(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("folderStructure") String folderStructure,
            @RequestParam("originalFolderName") String originalFolderName) {

        try {
            // 创建根目录（如果不存在）
            File rootDir = new File(uploadRootPath);
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }

            // 创建当前上传的文件夹
            String folderId = System.currentTimeMillis() + "_" + originalFolderName;
            String targetFolderPath = uploadRootPath + File.separator + folderId;
            File targetFolder = new File(targetFolderPath);
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }

            // 保存每个文件，保持原始目录结构
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    // 获取文件在文件夹中的相对路径
                    String relativePath = folderStructure;
                    // 处理路径分隔符，确保跨平台兼容
                    relativePath = relativePath.replace("/", File.separator).replace("\\", File.separator);

                    // 创建文件的目标路径
                    String fileName = file.getOriginalFilename();
                    String filePath = targetFolderPath + File.separator + relativePath + File.separator + fileName;

                    // 创建父目录
                    File destFile = new File(filePath);
                    if (!destFile.getParentFile().exists()) {
                        destFile.getParentFile().mkdirs();
                    }

                    // 保存文件
                    file.transferTo(destFile);
                }
            }

            // 记录文件夹路径（实际应用中可保存到数据库）
            folderPaths.put(folderId, targetFolderPath);

            // 返回成功信息
            Map<String, String> response = new HashMap<>();
            response.put("message", "文件夹上传成功");
            response.put("folderId", folderId);
            response.put("savedPath", targetFolderPath);

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件夹保存路径
     */
    @GetMapping("/folder/{folderId}/path")
    public ResponseEntity<?> getFolderPath(@PathVariable String folderId) {
        String path = folderPaths.get(folderId);
        if (path != null) {
            // 使用Java 8支持的HashMap初始化方式
            Map<String, String> response = new HashMap<>();
            response.put("folderId", folderId);
            response.put("path", path);
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("未找到文件夹: " + folderId);
        }
    }
}
